using MediatR;
using System;
using System.Threading;
using System.Threading.Tasks;
using Work.API.Applications.Write.Commands;
using Work.ErrorCode;
using Work.Infrastructure.Interfaces;

namespace Work.API.Applications.Write.CommandHandlers
{
    /// <summary>
    /// 更新处方明细处理器
    /// </summary>
    public class UpdatePrescriptionItemCommandHandler : IRequestHandler<UpdatePrescriptionItemCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Domain.PrescriptionItem> _prescriptionItemRepo;

        public UpdatePrescriptionItemCommandHandler(IBaseRepository<Domain.PrescriptionItem> prescriptionItemRepo)
        {
            _prescriptionItemRepo = prescriptionItemRepo;
        }

        public async Task<ApiResult<int>> Handle(UpdatePrescriptionItemCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 1. 获取处方明细
                var prescriptionItem = await _prescriptionItemRepo.GetById(request.PrescriptionItemId);
                if (prescriptionItem == null)
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "处方明细不存在";
                    result.Data = 0;
                    return result;
                }

                // 2. 检查是否已支付
                if (prescriptionItem.PaymentStatus == "已支付")
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "已支付的处方明细不能修改";
                    result.Data = 0;
                    return result;
                }

                // 3. 更新信息
                prescriptionItem.MedicineName = request.MedicineName;
                prescriptionItem.UnitPrice = request.UnitPrice;
                prescriptionItem.Quantity = request.Quantity;
                prescriptionItem.TotalAmount = request.UnitPrice * request.Quantity;

                var rows = await _prescriptionItemRepo.UpdateAsync(prescriptionItem);

                if (rows > 0)
                {
                    result.Code = ApiEnum.成功;
                    result.Message = "处方明细更新成功";
                    result.Data = prescriptionItem.PrescriptionItemId;
                }
                else
                {
                    result.Code = ApiEnum.失败;
                    result.Message = "处方明细更新失败";
                    result.Data = 0;
                }
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.失败;
                result.Message = $"更新失败：{ex.Message}";
                result.Data = 0;
            }

            return result;
        }
    }
}

